//
//  SupplierInfoViewController.m
//  EastMarket
//
//  Created by 李鹏程 on 16/11/17.
//  Copyright © 2016年 guoguo. All rights reserved.
//

#import "SupplierInfoViewController.h"

@interface SupplierInfoViewController ()
{
    UIView *viewBottom;
    UIView *viewShopping;
    UITabBarItem * item;
}
@property (strong, nonatomic) NSMutableArray<CALayer *> *redLayers;
@end

@implementation SupplierInfoViewController

- (NSMutableArray<CALayer *> *)redLayers {
    if (!_redLayers) {
        _redLayers = [NSMutableArray array];
    }
    return _redLayers;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"咪族购";
    self.view.backgroundColor = EastMarket_backgroundColor;
    _dataSourceArr = [[NSMutableArray alloc] init];

    globalManager.isAllProduct = true;
    
    _searchBar=[[UISearchBar alloc]initWithFrame:CGRectMake(SCREEN_WIDTH / 4,0,SCREEN_WIDTH * 3 / 4,40)];
    _searchBar.delegate=self;
    _searchBar.backgroundColor=[UIColor clearColor];
    _searchBar.placeholder=@"输入关键字进行查找";
    [_searchBar setSearchBarStyle:UISearchBarStyleDefault];
    self.navigationItem.titleView=_searchBar;
    pageIndex = 1;
    item = [self.tabBarController.tabBar.items objectAtIndex:3];
    [self initSellerInfoListUI];
    [self loadViewProductListOfSearch];
    [SVProgressHUD showWithStatus:@"加载中"];
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleCustom];
    [SVProgressHUD setForegroundColor:EastMarket_MainToneColor];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeClear];


    
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self showTabBar];
}

- (void)hideTabBar {
    if (self.tabBarController.tabBar.hidden == YES) {
        return;
    }
    UIView *contentView;
    if ( [[self.tabBarController.view.subviews objectAtIndex:0] isKindOfClass:[UITabBar class]] )
        contentView = [self.tabBarController.view.subviews objectAtIndex:1];
    else
        contentView = [self.tabBarController.view.subviews objectAtIndex:0];
    contentView.frame = CGRectMake(contentView.bounds.origin.x,  contentView.bounds.origin.y,  contentView.bounds.size.width, contentView.bounds.size.height + self.tabBarController.tabBar.frame.size.height);
    self.tabBarController.tabBar.hidden = YES;
    
}

- (void)showTabBar

{
    if (self.tabBarController.tabBar.hidden == NO)
    {
        return;
    }
    UIView *contentView;
    if ([[self.tabBarController.view.subviews objectAtIndex:0] isKindOfClass:[UITabBar class]])
        
        contentView = [self.tabBarController.view.subviews objectAtIndex:1];
    
    else
        
        contentView = [self.tabBarController.view.subviews objectAtIndex:0];
    contentView.frame = CGRectMake(contentView.bounds.origin.x, contentView.bounds.origin.y,  contentView.bounds.size.width, contentView.bounds.size.height - self.tabBarController.tabBar.frame.size.height);
    self.tabBarController.tabBar.hidden = NO;
    
}
- (void)initSellerInfoListUI {
    
    UIView* header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)];
    header.backgroundColor = [UIColor whiteColor];
    CALayer *bottomBorder = [CALayer layer];
    float height=header.frame.size.height-0.8f;
    float width=SCREEN_WIDTH;
    bottomBorder.frame = CGRectMake(0.0f, height, width, 0.8f);
    bottomBorder.backgroundColor =  EastMarket_bordColor.CGColor;
    [self.view addSubview:header];
    
    UITapGestureRecognizer *tapViewSelectSeller = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapViewSelectSeller:)];
    [header addGestureRecognizer:tapViewSelectSeller];

    UILabel *lblSellerName = [[UILabel alloc] initWithFrame:CGRectMake(25, 0, SCREEN_WIDTH - 2 * 25, header.frame.size.height)];
    lblSellerName.text = _sellerName;
    lblSellerName.font = [UIFont systemFontOfSize:14];
    lblSellerName.textAlignment = NSTextAlignmentCenter;
    [header addSubview:lblSellerName];
    
    UIImageView *rightImg = [[UIImageView alloc] initWithFrame:CGRectMake(lblSellerName.frame.origin.x + lblSellerName.frame.size.width + 1, (header.frame.size.height - 16) / 2, 16, 16)];
    rightImg.image = [UIImage imageNamed:@"rightArrow"];
    [header addSubview:rightImg];
    
    _tabView = [[UITableView alloc] initWithFrame:CGRectMake(0, header.frame.origin.y + header.frame.size.height + 2, SCREEN_WIDTH, SCREEN_HEIGHT - TabBarHeight - TopBarHeight - header.frame.size.height) style:UITableViewStylePlain];
    _tabView.showsVerticalScrollIndicator = false;
    _tabView.delegate = self;
    _tabView.dataSource = self;
    _tabView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tabView.backgroundColor = EastMarket_backgroundColor;
    [self setExtraCellLineHidden:_tabView];
    [self.view addSubview:_tabView];
    
    viewBottom = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT - TopBarHeight - TabBarHeight, SCREEN_WIDTH, TabBarHeight)];
    viewBottom.backgroundColor = [UIColor clearColor];
    [self.view addSubview:viewBottom];
    [self.view bringSubviewToFront:viewBottom];
    
    viewShopping = [[UIView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH * 3 / 5, SCREEN_HEIGHT - TopBarHeight - TabBarHeight, SCREEN_WIDTH / 5, TabBarHeight)];
    viewShopping.backgroundColor = [UIColor clearColor];
    [self.view addSubview:viewShopping];
}

// 关键字搜索
- (void)loadViewProductListOfSearch {
    [NSThread detachNewThreadSelector:@selector(callServerProductListOfSearch) toTarget:self  withObject:Nil];
}

- (void)callServerProductListOfSearch {
    
    pageSize = 20;
    NSDictionary *dicOfProductWithSeller = [AppServiceInterface productOfSearchWithSeller:_searchBar.text productCatePath:@"" order:@" " page:pageIndex pageSize:pageSize sellerId:_sellerId];
    [self performSelectorOnMainThread:@selector(updateProductListOfSearch:) withObject:dicOfProductWithSeller waitUntilDone:NO];
}

- (void)updateProductListOfSearch:(NSDictionary *)dic {
    
    [SVProgressHUD dismiss];
    if (dic && [[dic objectForKey:@"success"] integerValue] == 1) {
        if ([[[dic objectForKey:@"data"] objectForKey:@"page"] integerValue] == 1) {
            [_dataSourceArr removeAllObjects];
        }
        [_dataSourceArr addObjectsFromArray:[[dic objectForKey:@"data"] objectForKey:@"results"]];
        [_tabView reloadData];
    } else if (dic && [[dic objectForKey:@"success"] integerValue] != 1) {
    
        [GlobalUnit showAlertHint:@"温馨提示！" message:[NSString stringWithFormat:@"%@", [dic objectForKey:@"msg"]]];
    } else {
    
        [GlobalUnit showAlertHint:@"温馨提示！" message:@"请求服务器失败，请稍后重试"];
    }
}

// 添加常用料
- (void)callServerCustomerAdd:(NSString *)itemId {
    
    NSDictionary *resultOfCustomerAdd = [AppServiceInterface CustomerItemAdd:itemId];
    [self performSelectorOnMainThread:@selector(updateUIAfterCustomerAdd:) withObject:resultOfCustomerAdd waitUntilDone:NO];
}

- (void)updateUIAfterCustomerAdd:(NSDictionary *)dic {
    
    if (dic && [[dic objectForKey:@"success"] integerValue] == 1) {
        [GlobalUnit showMessage:[NSString stringWithFormat:@"%@", [dic objectForKey:@"msg"]]];
        [NSThread detachNewThreadSelector:@selector(callServerProductListOfSearch) toTarget:self  withObject:Nil];
    } else if (dic && [[dic objectForKey:@"success"] integerValue] == 0) {
        
        [GlobalUnit showAlertHint:@"温馨提示！" message:[NSString stringWithFormat:@"%@", [dic objectForKey:@"msg"]]];
    } else {
        
        [GlobalUnit showAlertHint:@"温馨提示！" message:@"请求服务器失败，请稍后重试"];
    }
}

// 取消常用料
- (void)callServerCustomerDelete:(NSString *)itemId {
    
    NSDictionary *resultOfCustomerDel = [AppServiceInterface CustomerItemDelete:itemId];
    [self performSelectorOnMainThread:@selector(updateUIAfterCustomerAdd:) withObject:resultOfCustomerDel waitUntilDone:NO];
}


// 添加商品到购物车
- (void)loadViewCartItem:(NSString *)productID productNum:(NSInteger)productNum {
    
    _strProductID = productID;
    _productNum = productNum;
    [NSThread detachNewThreadSelector:@selector(callServerGetPCartItem) toTarget:self  withObject:Nil];
}

- (void)callServerGetPCartItem {
    
    NSDictionary *dict = [AppServiceInterface cartItem:_strProductID itemNum:_productNum];
    [self performSelectorOnMainThread:@selector(updateCartItem:) withObject:dict waitUntilDone:NO];
}

- (void)updateCartItem:(NSDictionary *)dic {
    
    if (dic && [[dic objectForKey:@"success"] integerValue] == 1) {
        if (![[dic objectForKey:@"data"] isKindOfClass:[NSNull class]]) {
            //            [_tvDetailList reloadData];
            item.badgeValue = [NSString stringWithFormat:@"%@", [[dic objectForKey:@"data"] objectForKey:@"cartItemNum"]];
            [NSThread detachNewThreadSelector:@selector(callServerProductListOfSearch) toTarget:self  withObject:Nil];
            
        }
    }
}

#pragma mark -- UITableViewDelegate &  UITableViewDatasource

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 104;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return _dataSourceArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *cellIdentifier = @"cell";
    ProductOrMaterialsViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell == nil) {
        cell = [[ProductOrMaterialsViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor whiteColor];
    NSInteger cur = [indexPath row];
    NSDictionary *sellerInfoDic = [_dataSourceArr objectAtIndex:cur];
    
    [cell.imgProductIcon sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@", [sellerInfoDic objectForKey:@"itemPic"]]] placeholderImage:[UIImage imageNamed:@"NoProductImage"]];
    cell.lblProductName.text = [NSString stringWithFormat:@"%@", [sellerInfoDic objectForKey:@"sellerName"]];
    cell.lblProductPrice.text = [NSString stringWithFormat:@"%.2lf元", [[sellerInfoDic objectForKey:@"itemPrice"] floatValue]];
    cell.lblProductSupplier.text = [NSString stringWithFormat:@"%@", [sellerInfoDic objectForKey:@"sellerName"]];
    cell.lblProductNum.text = [NSString stringWithFormat:@"%@", [sellerInfoDic objectForKey:@"cartNum"]];
    _favor = [NSString stringWithFormat:@"%@", [sellerInfoDic objectForKey:@"favor"]];
    
    NSString *itemStr = [NSString stringWithFormat:@"%@", [sellerInfoDic objectForKey:@"id"]];
    if (_favor.integerValue == 0) {
        [cell.btnFavorite setBackgroundImage:[UIImage imageNamed:@"star"] forState:UIControlStateNormal];
    } else if(_favor.integerValue == 1){
        
        [cell.btnFavorite setBackgroundImage:[UIImage imageNamed:@"star-active"] forState:UIControlStateNormal];
    }

    cell.block=^(CGPoint point)
    {
        CGPoint startPoint = [self.view convertPoint:point fromView:_tabView];
        CGPoint endpoint=[self.view convertPoint:viewShopping.center fromView:viewBottom];
        [self initCHLayerFromPoint:startPoint toPoint:endpoint];
    };
    
    cell.btnFavoriteClick = ^() {
        debugLog(@"%ld", indexPath.row);
        debugMethod();
        if (_favor.integerValue == 0) {
            [NSThread detachNewThreadSelector:@selector(callServerCustomerAdd:) toTarget:self  withObject:itemStr];
            [_tabView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
        } else if(_favor.integerValue == 1){
            
            UIAlertController *alerController = [UIAlertController alertControllerWithTitle:@"温馨提示！" message:@"您确定要取消当前收藏商品吗？" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            
            UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"是的" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [NSThread detachNewThreadSelector:@selector(callServerCustomerDelete:) toTarget:self  withObject:itemStr];
                [_tabView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
            }];
            
            [alerController addAction:cancleAction];
            [alerController addAction:defaultAction];
            [self  presentViewController:alerController animated:YES completion:nil];
        }

    };
    
    cell.btnNumReduceClick = ^() {
        debugMethod();
        debugLog(@"%ld", indexPath.row);
        if (cell.lblProductNum.text.integerValue > 0) {
            
            [self loadViewCartItem:[NSString stringWithFormat:@"%@", [sellerInfoDic objectForKey:@"id"]] productNum:-1];
            [_tabView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
        } else {
            
            [GlobalUnit showAlertHint:@"温馨提示！" message:@"当前商品数目为0"];
        }

    };
    
    cell.btnNumAddClick = ^() {
        debugMethod();
        debugLog(@"%ld", indexPath.row);
        [self loadViewCartItem:[NSString stringWithFormat:@"%@", [sellerInfoDic objectForKey:@"id"]] productNum:1];
        [_tabView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
    };
    
    return cell;
}

/*
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    
    UIView *viewHeader = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44)];
    viewHeader.backgroundColor = [UIColor whiteColor];
    CALayer *bottomBorder = [CALayer layer];
    float height=viewHeader.frame.size.height-0.8f;
    float width=viewHeader.frame.size.width;
    bottomBorder.frame = CGRectMake(0.0f, height, width, 0.8f);
    bottomBorder.backgroundColor =  EastMarket_bordColor.CGColor;
    [viewHeader.layer addSublayer:bottomBorder];
    return viewHeader;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 44.0f;
}
*/
//多余的空行上不显示分割线
- (void)setExtraCellLineHidden: (UITableView *)tableView{
    UIView *view =[ [UIView alloc]init];
    view.backgroundColor = [UIColor clearColor];
    [tableView setTableFooterView:view];
    [tableView setTableHeaderView:view];
}

- (void)initCHLayerFromPoint:(CGPoint)startPoint toPoint:(CGPoint)endPoint {
    
    CALayer *chLayer = [[CALayer alloc] init];
    [self.redLayers addObject:chLayer];
    chLayer.frame = CGRectMake(startPoint.x, startPoint.y, 15, 15);
    chLayer.cornerRadius = CGRectGetWidth(chLayer.frame)/2.f;
    chLayer.backgroundColor = [UIColor redColor].CGColor;
    [self.view.layer addSublayer:chLayer];
    
    CAKeyframeAnimation *CHAnimation=[CAKeyframeAnimation animationWithKeyPath:@"position"];
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, startPoint.x, startPoint.y);
    CGPathAddQuadCurveToPoint(path, NULL, endPoint.x, startPoint.y, endPoint.x, endPoint.y);
    
    CHAnimation.path = path;
    CHAnimation.removedOnCompletion = NO;
    CHAnimation.fillMode = kCAFillModeBoth;
    CHAnimation.duration = 0.5;
    CHAnimation.delegate = self;
    [chLayer addAnimation:CHAnimation forKey:nil];
}


- (void)tapViewSelectSeller:(UIGestureRecognizer *)tap {

    [self.navigationController popViewControllerAnimated:true];
}

-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    [self.redLayers[0] removeFromSuperlayer];
    [self.redLayers removeObjectAtIndex:0];
}

#pragma mark --  UISearchBarDelegate & UISearchResultsUpdating delegate
// 取消按钮点击的回调
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    
    debugMethod();
    [_searchBar resignFirstResponder];
    _searchBar.showsCancelButton = false;
}
// 搜索按钮点击的回调
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    
    debugMethod();
    [_searchBar resignFirstResponder];
//    [self loadViewProductListOfSearch:_searchBar.text productCatePath:@" " order:_strProductID];
    [NSThread detachNewThreadSelector:@selector(callServerProductListOfSearch) toTarget:self  withObject:Nil];
}

- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {

    debugMethod();
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    
    debugMethod();
    _searchBar.showsCancelButton = true;
    
    return YES;
}

- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {
    
    debugMethod();
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
